#include "resetdialog.h"
#include "ui_resetdialog.h"
#include<QLineEdit>

ResetDialog::ResetDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ResetDialog)
{
    ui->setupUi(this);

    connect(ui->user_lineEdit,&QLineEdit::editingFinished,this,[this](){
        checkUserVaild();
    });
    connect(ui->email_lineEdit,&QLineEdit::editingFinished,this,[this](){
        checkEmailVaild();
    });
    connect(ui->pwd_lineEdit,&QLineEdit::editingFinished,this,[this](){
        checkPassVaild();
    });
    connect(ui->varify_lineEdit,&QLineEdit::editingFinished,this,[this](){
        checkVarifyVaild();
    });

    initHttpHandlers();
    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_reset_mod_finish,this,&ResetDialog::slot_reset_mod_finish);

    //设置密码可见性
    ui->pass_visible->setCursor(Qt::PointingHandCursor);
    ui->pass_visible->SetState("unvisible","unvisible_hover","","visible","visible_hover","");
    ui->pwd_lineEdit->setEchoMode(QLineEdit::Password);
    connect(ui->pass_visible,&ClickedLabel::clicked,this,[this](){
        auto state =ui->pass_visible->GetCurState();
        if(state==ClickLbState::Normal){
            ui->pwd_lineEdit->setEchoMode(QLineEdit::Password);
        }
        else{
            ui->pwd_lineEdit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });
}

ResetDialog::~ResetDialog()
{
    delete ui;
}

void ResetDialog::initHttpHandlers()
{
    _handlers.insert(ReqId::ID_GET_VARIFY_CODE,[this](QJsonObject jsonObj){
        int error=jsonObj["error"].toInt();
        if(error!=ErrorCodes::SUCCESS){
            showTip(tr("调用参数错误"),false);
            return;
        }
        auto email=jsonObj["email"].toString();
        showTip(tr("验证码已发送到邮箱"),true);
        //email值
        qDebug()<<"email is"<<email;
    });

    _handlers.insert(ReqId::ID_RESET_PWD,[this](QJsonObject jsonObj){
        int error =jsonObj["error"].toInt();
        if(error!=ErrorCodes::SUCCESS){
            showTip(tr("调用参数错误"),false);
            return;
        }

        auto email=jsonObj["email"].toString();
        showTip(tr("重置成功，点击返回登录界面"),true);
        qDebug()<<"email is"<<email;
        qDebug()<<"uid is "<<jsonObj["uid"].toString();

    });
}

void ResetDialog::showTip(QString str, bool b_ok)
{
    if(b_ok){
        ui->error_label->setProperty("state","normal");
    }
    else{
        ui->error_label->setProperty("state","err");
    }
    ui->error_label->setText(str);
    repolish(ui->error_label);
}

bool ResetDialog::checkUserVaild()
{
    if(ui->user_lineEdit->text()==""){
        AddTipErr(TipErr::TIP_USER_ERR,tr("用户名不能为空"));
        return false;
    }
    DelTipErr(TipErr::TIP_USER_ERR);
    return true;
}

bool ResetDialog::checkEmailVaild()
{
    auto email=ui->email_lineEdit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match=regex.match(email).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_EMAIL_ERR,tr("邮箱不正确"));
        return false;
    }
    DelTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}

bool ResetDialog::checkPassVaild()
{
    auto pass=ui->pwd_lineEdit->text();
    if(pass.length()<6||pass.length()>15){
        AddTipErr(TipErr::TIP_PWD_ERR,tr("密码长度应为6~15"));
        return false;
    }
    //正则表达式设置密码
    QRegularExpression regExp("[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match =regExp.match(pass).hasMatch();
    if(!match){
        AddTipErr(TipErr::TIP_PWD_ERR,tr("不能包含非法字符"));
        return false;
    }
    DelTipErr(TipErr::TIP_PWD_ERR);
    return true;
}

bool ResetDialog::checkVarifyVaild()
{
    auto varify=ui->varify_lineEdit->text();
    if(varify.isEmpty()){
        AddTipErr(TipErr::TIP_VARIFY_ERR,"验证码不能为空");
        return false;
    }
    DelTipErr(TipErr::TIP_VARIFY_ERR);
    return true;
}

void ResetDialog::AddTipErr(TipErr te, QString tips)
{
    _tip_errs[te]=tips;
    showTip(tips,false);
}

void ResetDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if(_tip_errs.empty()){
        ui->error_label->clear();
        return;
    }
    showTip(_tip_errs.first(),false);
}

void ResetDialog::slot_reset_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    if(err!=ErrorCodes::SUCCESS){
        showTip("网络请求错误",false);
        return;
    }
    QJsonDocument json_doc=QJsonDocument::fromJson(res.toUtf8());
    if(json_doc.isNull()){
        showTip("json解析错误",false);
        return;
    }
    if(!json_doc.isObject()){
        showTip("json解析错误",false);
        return;
    }
    _handlers[id](json_doc.object());
    return;
}

void ResetDialog::on_varify_btn_clicked()
{

    auto email=ui->email_lineEdit->text();
    auto check=checkEmailVaild();
    if(!check){
        return;
    }
    qDebug()<<"get varify code";
    QJsonObject json_obj;
    json_obj["email"]=email;
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/get_varifyCode"),json_obj,
                                        ReqId::ID_GET_VARIFY_CODE,Modules::RESETMOD);
}

void ResetDialog::on_confirm_btn_clicked()
{
    bool valid=checkUserVaild();
    if(!valid){
        return;
    }
    valid=checkEmailVaild();
    if(!valid){
        return;
    }
    valid=checkVarifyVaild();
    if(!valid){
        return;
    }
    valid=checkPassVaild();
    if(!valid){
        return;
    }

    QJsonObject json_obj;
    json_obj["user"]=ui->user_lineEdit->text();
    json_obj["email"]=ui->email_lineEdit->text();
    json_obj["passwd"]=xorString(ui->pwd_lineEdit->text());
    json_obj["varify"]=ui->varify_lineEdit->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/reset_pwd"),
                                        json_obj,ReqId::ID_RESET_PWD,Modules::RESETMOD);
}


void ResetDialog::on_cancel_btn_clicked()
{
    emit switchLogin();
    return;
}

